package com.example.controller;

import com.example.pojo.dto.JobSeekerInformationDTO;
import com.example.pojo.dto.JobSeekerUserInfoDTO;
import com.example.pojo.entity.JobSeeker;
import com.example.service.JobSeekerService;
import com.example.util.AESUtil;
import com.example.util.JWTUtils;
import com.example.vo.Result;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.print.attribute.standard.ReferenceUriSchemesSupported;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 小岁
 * @version 2023/10/1 21:15
 */
@RestController
@RequestMapping("jobSeeker")
public class JobSeekerController {

    private static final String SECRET = "success";//盐值
    private static String SECRET_KEY;

    @Autowired
    private JobSeekerService jobSeekerService;

    @Autowired
    private RedisTemplate redisTemplate;



    @PostMapping("login")
    public Result login( String jsaccount, String jscipher) {
        ValueOperations vop = redisTemplate.opsForValue();
        JobSeeker jobSeeker = jobSeekerService.login(jsaccount);

        if (jobSeeker == null) {
            return new Result(404, "用户名不存在");
        }
        jscipher = Jwts.builder().claim("password",jscipher).signWith(SignatureAlgorithm.HS256,SECRET).compact();
        //校验
        String pwd = jscipher;
        //查数据的时候就要加密了
//        String pwd = DigestUtil.md5Hex(jscipher);
//        String pwd = SaltMD5Util.generateSaltPassword(jscipher);

        //user是存在的
        if (!jobSeeker.getJsCipher().equals(pwd)) {
            return new Result(500, "密码错误");
        }

        //服务器创建一个token
        String token = JWTUtils.geneJsonWebToken(jobSeeker);

        Integer userId= jobSeeker.getId();
        vop.set("js_"+userId,token);
        redisTemplate.expire("js_"+userId,1, TimeUnit.HOURS);
        return new Result(200, "登录成功",userId,token);
//        return new Result(200, "登录成功", token);
    }

    @GetMapping("checkAccount/{jsaccount}")
    public Result checkAccount(@PathVariable("jsaccount") String jsaccount){
//        System.out.println(jsaccount);

        JobSeeker jobSeeker = jobSeekerService.login(jsaccount);
        if (jobSeeker!=null){
            return new Result(500,"用户名已存在");
        }else {
            return new Result(200,"用户名可用");
        }
    }
    @PostMapping("register/{jsaccount}/{jscipher}")
    public Result register(@PathVariable("jsaccount") String jsaccount, @PathVariable("jscipher") String jscipher){
//        System.out.println("============================="+jsaccount+":"+jscipher);

        JobSeeker jobSeeker = jobSeekerService.login(jsaccount);
        if (jobSeeker!=null){
            return new Result(500,"用户名已存在");
        }else {

            jscipher = Jwts.builder().claim("password",jscipher).signWith(SignatureAlgorithm.HS256,SECRET).compact();

//            System.out.println("======================"+jscipher);
//            return null;
            int count = jobSeekerService.register(jsaccount,jscipher);

            if(count!=0){
                return new Result(200,"注册成功");
            }else{
                return new Result(500,"注册失败");

            }
        }
    }

    @PostMapping("verify")
    public Result veriFY(){
        SECRET_KEY = AESUtil.gainKey();
        return new Result(200,"密钥",SECRET_KEY);
    }


    @PostMapping("curric/{id}")
    public Result CurriculumByJS(@PathVariable("id") Integer id){
        JobSeekerUserInfoDTO jobSeeker = jobSeekerService.findJSById(id);
        return new Result(200,"求职者查询成功",jobSeeker);
    }

    @PostMapping("update")
    public Result updateInformation(JobSeekerInformationDTO jobSeekerInformationDTO){
        System.out.println(jobSeekerInformationDTO);
        int count = jobSeekerService.updateInformation(jobSeekerInformationDTO);
        if (count==1){
            return new Result(200,"更新成功");
        }else {
            return new Result(500,"更新失败");
        }

    }

    @PostMapping("findByIdNew/{id}")
    public Result findById(@PathVariable("id") Integer id){
        JobSeeker jobSeeker = jobSeekerService.findJSByIdNew(id);
        return new Result(200,"查询成功",jobSeeker);
    }

    @PostMapping("amendJs")
    public Result amendJs(@RequestHeader("id") Integer id,
                          @RequestHeader("token") String token,
                          @RequestBody Map<String, Object> requestBody){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 从请求体中获取需要的参数
        String username = (String) requestBody.get("username");
        String telephone = (String) requestBody.get("phone");
        String password = (String) requestBody.get("password");
        String email = (String) requestBody.get("email");
        Date birthday = null;
        try {
            birthday = dateFormat.parse((String) requestBody.get("birthday"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        String sex = (String) requestBody.get("sex");
        String brithplace = (String) requestBody.get("birthplace");
        Integer newSex=0;
        String cipher;
        if (sex.equals("男")){
            newSex = 1;
        } else if (sex.equals("女")){
            newSex = 0;
        }
        JobSeeker jobSeeker = jobSeekerService.findJSByIdNew(id);
        if (password.equals(jobSeeker.getJsCipher())){
            cipher = password;
        } else {
            System.out.println("修改了密码");
            System.out.println(password);
            cipher = Jwts.builder().claim("password",password).signWith(SignatureAlgorithm.HS256,SECRET).compact();
            System.out.println(cipher);
        }

        int js = jobSeekerService.amendJs(id,username,telephone,cipher,email,birthday,newSex,brithplace);
        if (js==1){
            return new Result(200,"修改成功");
        }
        return new Result(500,"修改失败");
    }


    @PostMapping("/uploadImage/{id}")
    public String uploadImage(@RequestParam("file") MultipartFile file,@PathVariable("id") Integer id) {
        try {
            // 获取当前项目所在路径
            String rootPath = new File("").getAbsolutePath();
            System.out.println(rootPath);
//            System.out.println(10/0);
            // 设置保存图片的目录
            String uploadDir = rootPath + "/src/main/webapp/assets/img/headPortrait/";

            // 如果目录不存在，则创建目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + getFileExtension(file);
            // 创建新的文件
            File dest = new File(uploadDir + fileName);
            // 将上传的文件保存到新的文件中
            file.transferTo(dest);

            String newFile = "/dev/assets/img/headPortrait/"+fileName;
            JobSeeker jobSeeker = new JobSeeker();
            jobSeeker.setId(id);
            jobSeeker.setAvatar(newFile);
            jobSeekerService.newAvatar(jobSeeker);

            // 返回保存文件的路径
            return uploadDir + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    // 获取文件的后缀名
    private String getFileExtension(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf('.'));
    }


}
